import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.*;


public class CreateTable {

    Connection conn = null;
    Configuration conf = null;

    @Before
    public void init() throws IOException {
        //获取配置文件对象
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "linux121,linux122");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        //通过conf获取到hbase集群的连接
        conn = ConnectionFactory.createConnection(conf);
    }

    @Test
    public void createTable() throws IOException {
        //创建表
        //获取HBaseAdmin对象，用来创建表
        HBaseAdmin admin = (HBaseAdmin) conn.getAdmin();
        //创建表描述器
        HTableDescriptor relation = new HTableDescriptor(TableName.valueOf("relation"));
        //指定列族
        relation.addFamily(new HColumnDescriptor("friends"));
        //创建表
        admin.createTable(relation);
        System.out.println("relation表创建成功");
    }

    @Test
    public void putData() throws IOException {
        //插入测试数据
        //获取一个Table对象
        Table relation = conn.getTable(TableName.valueOf("relation"));
        //准备put对象，指定rowkey为用户id
        Put put1 = new Put(Bytes.toBytes("uid1"));
        put1.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid2"), Bytes.toBytes("uid2"));
        put1.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid3"), Bytes.toBytes("uid3"));
        Put put2 = new Put(Bytes.toBytes("uid2"));
        put2.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid1"), Bytes.toBytes("uid1"));
        Put put3 = new Put(Bytes.toBytes("uid3"));
        put3.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid1"), Bytes.toBytes("uid1"));
        List<Put> putList = new ArrayList<>();
        putList.add(put1);
        putList.add(put2);
        putList.add(put3);
        //插入数据
        relation.put(putList);
        relation.close();
        System.out.println("测试数据已插入到relation表中");
    }


    @After
    public void release() {
        //释放连接
        if (conn != null) {
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
